﻿package com.thorqq.magictimer.misc;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import com.thorqq.magictimer.util.Util;

import dalvik.system.DexClassLoader;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

public class PluginInvoke
{
    static Class<?> localClass;
    static private Object instance;

    static public void LoadAPK(Context context, Bundle paramBundle, String dexpath)
    {
        ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
        DexClassLoader localDexClassLoader = new DexClassLoader(dexpath, 
                Util.getSDCardDir().getAbsolutePath(), null, localClassLoader);
        try
        {
            //查找所有的activities
            PackageInfo plocalObject = context.getPackageManager()
                    .getPackageArchiveInfo(dexpath, PackageManager.GET_ACTIVITIES);

            if ((plocalObject.activities != null) && (plocalObject.activities.length > 0))
            {
                //TODO  取第一个activity
                String activityname = plocalObject.activities[0].name;
                Util.log("activityname = " + activityname);

                //创建对象
                localClass = localDexClassLoader.loadClass(activityname);// 结果："com.example.fragmentproject.FristActivity"
                Constructor<?> localConstructor = localClass.getConstructor(new Class[] {});
                instance = localConstructor.newInstance(new Object[] {});
                Util.log("instance = " + instance);

//                //调用test函数
//                Method des = localClass.getMethod("test");
//                des.invoke(instance);

                //调用setActivity
                Method localMethodSetActivity = localClass.getDeclaredMethod("setActivity",
                        new Class[] { Activity.class });
                localMethodSetActivity.setAccessible(true);
                localMethodSetActivity.invoke(instance, new Object[] { context });

                //调用onCreate
                Method methodonCreate = localClass.getDeclaredMethod("onCreate",
                        new Class[] { Bundle.class });
                methodonCreate.setAccessible(true);
                methodonCreate.invoke(instance, paramBundle);
            }
        } catch (Exception ex)
        {
            Util.log_ex(ex);
        }
    }
}